/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: ProcessEpolicy
 * Author:   ThinkPad
 * Date:     2020/6/24 17:06
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.jt.www.queue.process;

import com.jt.www.enums.issue.IssueEnum;
import com.jt.www.enums.issue.PolicyInterfaceEnum;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.issue.entity.IssueRecordEntity;
import com.jt.www.util.DateUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * @author xq.wu
 * @Description 济宁学平电子保单 使用统一下载格式
 * 食品险-中华联合电子保单 使用统一下载格式
 * 统一带url的电子保单下载及绑定资源
 * 需要数据交换中心返回的报文中添加
 * 【公司编码companyCode】
 * 【电子保单地址url】
 * 【投保成功标识ResponseCode(0000)】
 * @create 2020/6/24
 * @since 1.0.0
 */
@Service
public class ProcessEpolicy extends ElecPolicyProcess implements InitializingBean {

    public static final Logger log = LoggerFactory.getLogger(ProcessEpolicy.class);

    @Override
    public void afterPropertiesSet() throws Exception {
        IssuePolicyIfCodeFactory.register(PolicyInterfaceEnum.CODE_19.getIfCode(), this);
        IssuePolicyIfCodeFactory.register(PolicyInterfaceEnum.CODE_20.getIfCode(), this);
    }

    @Override
    public Boolean process(Element rootElement, String ifCode) {
        // 解析xml，封装数据
        Element reqPacket = getReqPacket(rootElement);
        Element respPacket = getRespPacket(rootElement);
        IssueEnum issueEnum = IssueEnum.getIssueEnum(ifCode);
        String proCode = issueEnum.getProCode();
        String currentTime = DateUtils.getCurrentTime();
        // 投保单号
        String tbNo = rootElement.element("ApplicationFormCode").getStringValue();
        // 保单号
        String policyNo = rootElement.element("PolicyNo").getStringValue();
        //出单公司编码
        String companyCode = rootElement.element("companyCode").getStringValue();
        // 入库
        // 入库之前首先判断 是否已经入库  根据投保单号判断
        IssueRecordEntity issueRecordEntity = new IssueRecordEntity();
        issueRecordEntity.setApplicationFormCode(tbNo);
        List<IssueRecordEntity> select = issueRecordEntityMapper.select(issueRecordEntity);
        if (select != null && select.size() > 0) {
            log.info("系统时间：{}, {}投保单号是 {} 的消息发送重复", issueEnum.getDesc(), currentTime, tbNo);
            // 消息重复，消息直接消费完成。
            return true;
        }
        issueRecordEntity.setPolicyNo(policyNo);
        issueRecordEntity.setCompanyCode(companyCode);
        issueRecordEntity.setProCode(proCode);
        issueRecordEntity.setReqPacket(reqPacket.asXML());
        issueRecordEntity.setResPacket(respPacket.asXML());
        issueRecordEntity.setSendStatus("1");
        String status = rootElement.element("ResponseCode").getStringValue();
        if ("0000".equals(status)) {
            status = "2";
        } else {
            status = "3";
        }
        // 数据中心返回 的投保单状态
        issueRecordEntity.setStatus(status);
        issueRecordEntity.setCreateTime(currentTime);
        issueRecordEntity.setUpdateTime(currentTime);
        issueRecordEntity.setIfCode(issueEnum.getIfCode());
        issueRecordEntityMapper.insert(issueRecordEntity);
        if ("3".equals(status)) {
            // 出单失败，消息直接消费完成，在入库的逻辑后边。
            return true;
        }
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子保单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";
        issuePolicyLogEntity.setApplicationFormCode(tbNo);
        issuePolicyLogEntity.setPolicyNo(policyNo);
        issuePolicyLogEntity.setType("1");
        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(proCode);
        String url = rootElement.element("url").getStringValue();
        log.info("{}电子保单地址{}", issueEnum.getDesc(), url);
        // 拼装下载报文
        Document doc = DocumentHelper.createDocument();
        Element info = doc.addElement("body");
        info.addElement("url").addText(url);
        issuePolicyLogEntity.setParam(info.asXML());
        issuePolicyLogEntity.setTimes(0);
        issuePolicyLogEntity.setIfCode(issueEnum.getIfCode());
        issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
        // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
        issueRecordEntity.setSendStatus("2");
        issueRecordEntityMapper.updateByPrimaryKeySelective(issueRecordEntity);
        //调用接口,请求数据交换中心，下载电子保单
        try {
            String eUrl = info.asXML().replace("&amp;", "&");
            log.info("{}的投保单号是 {}, 保单下载参数：{}", issueEnum.getDesc(), tbNo, eUrl);
            // 请求下载保单，成功更新
            String seqNo = Long.toString(Math.abs(new Random().nextLong()));
            ResponseEntity<String> responseEntity = dexClient.text("edu", "20190516022", "1.0", seqNo, eUrl);
            if (null == responseEntity) {
                log.info("{}的投保单号是 {}, 保单下载失败", issueEnum.getDesc(), tbNo);
                return false;
            }
            log.info("{}的投保单号是 {}, 保单下载返回值：{}, {}", issueEnum.getDesc(), tbNo, responseEntity.getStatusCodeValue(), responseEntity.getBody());
            consumeStatus = "2";
            String fileId = responseEntity.getBody();
            issuePolicyLogEntity.setStatus(consumeStatus);
            // 下载成功，更新数据库，绑定资源
            log.info(" 下载消息 fileId ：{}", issueEnum.getDesc(), fileId);
            bindingResources(tbNo, fileId, issuePolicyLogEntity);
            return true;
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}